package com.shigen.demo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shigen.demo.bean.Result;
import com.shigen.demo.entity.ProjectData;
import com.shigen.demo.entity.req.ProjectDataReq.QueryItem;
import com.shigen.demo.mapper.ProjectDataMapper;
import com.shigen.demo.service.IProjectDataService;
import com.shigen.demo.util.IPUtil;
import com.shigen.demo.util.UserAgentUtil;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ProjectDataServiceImpl extends ServiceImpl<ProjectDataMapper, ProjectData> implements IProjectDataService {

  @Resource
  private JdbcTemplate jdbcTemplate;

  @Override
  public Result<JSONObject> getProjectData(QueryItem queryItem) {

    // 获得数据的总数
    String id = queryItem.getId();
    QueryWrapper<ProjectData> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq(StrUtil.isNotEmpty(id), "proj_id", id).eq("is_del", false);
    Integer count = getBaseMapper().selectCount(queryWrapper);

    JSONObject result = new JSONObject();
    result.put("total", count);
    result.put("pagenum", queryItem.getPagenum());
    result.put("pagesize", queryItem.getPagesize());
    result.put("list", this.projectDataMap(queryItem));
    result.put("keys", this.projectDataKeys(id));
    return Result.ok(result);
  }

  public Result addProjectData(ProjectData projectData, HttpServletRequest request) {
    String projId = projectData.getProjId();
    if (StrUtil.isBlank(projId)) {
      return Result.err("表单的id未插入");
    }
    String ip = IPUtil.getIp(request);
    String position = "";
    try {
      position = IPUtil.getCityInfo(ip);
    } catch (IOException e) {
      e.printStackTrace();
      return Result.err("IP地址获取失败或地址解析失败");
    }
    projectData.setIp(ip);
    projectData.setPosition(position);

    String os = "";
    String browser = "";

    String userAgent = UserAgentUtil.getUserAgent(request);
    if (StrUtil.isNotBlank(userAgent)) {
      os = UserAgentUtil.getOs(userAgent);
      browser = UserAgentUtil.getBorderName(userAgent);
    }
    projectData.setOs(os);
    projectData.setBrowser(browser);

    int insert = getBaseMapper().insert(projectData);
    return insert > 0 ? Result.ok("已成功提交，谢谢参与") : Result.err("提交失败，请联系管理员");
  }

  public int deleteBatchIds(List<Integer> ids) {
    if (CollectionUtil.isEmpty(ids)) {
      return 0;
    } else {
      return getBaseMapper().deleteBatchIds(ids);
    }
  }

  public int update(ProjectData projectData) {
    return getBaseMapper().updateById(projectData);
  }

  public List<String> projectDataKeys(String id) {
    // 返回的keys作为前端遍历循环的prop 和数据库的字段名对应
    List<String> keys = new ArrayList<>();
    // keys.add("index");
    keys.add("createTime");
    keys.add("ip");
    keys.add("position");
    keys.add("browser");
    keys.add("os");
    keys.add("murmur");
    keys.add("timeUse");

    // 添加data的所有key
    Map<String, Object> dataMap = jdbcTemplate.queryForMap("select json_keys(data) as dataKeys from project_data where proj_id = ? limit 0,1", id);
    if (CollectionUtil.isNotEmpty(dataMap)) {
      JSONArray jsonArray = JSONArray.parseArray((String) dataMap.get("dataKeys"));
      List<String> ts = jsonArray.toJavaList(String.class);
      keys.addAll(ts);
    }
    return keys;
  }

  public List<Map<String, Object>> projectDataMap(QueryItem queryInfo) {
    List<Map<String, Object>> resultMaps = new ArrayList<>();
    Page<ProjectData> page = new Page<>(queryInfo.getPagenum(), queryInfo.getPagesize());

    // 分页查询数据
    String id = queryInfo.getId();
    IPage<ProjectData> dataIPage = lambdaQuery().eq(StrUtil.isNotBlank(id), ProjectData::getProjId, id).page(page);
    // 获得分页的数据
    List<ProjectData> records = dataIPage.getRecords();
    // 每一条数据需要转成map的格式

    if (CollectionUtil.isNotEmpty(records)) {
      records.forEach(projectData -> {
        Map<String, Object> objectMap = BeanUtil.beanToMap(projectData);
        // 单独处理json类型的data
        if (objectMap.get("data") != null) {
          String data = (String) objectMap.get("data");
          Map map = JSONObject.parseObject(data, Map.class);
          objectMap.putAll(map);
          objectMap.remove("data");
        }
        resultMaps.add(objectMap);
      });
    }
    return resultMaps;
  }

}
